package com.merlin.demo_wellshape.controller;

import com.merlin.demo_wellshape.pojo.ResponseMessage;
import com.merlin.demo_wellshape.pojo.User;
import com.merlin.demo_wellshape.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Base64;

@RestController // 接口方法返回对象，转换成JSON数据
@RequestMapping("/user") // 映射路径
public class UserController {

    @Autowired // 自动注入
    UserServiceImpl userService;

    // REST
    // 创建用户
    @PostMapping // URL：localhost:8080/user  method:post
    public ResponseMessage<User> createUser(@RequestParam String userPhone, @RequestParam String password) {
        User user = new User();
        user.setUserPhone(userPhone);
        user.setPassword(password);
        return userService.saveUser(user);
    }

    // 根据ID获取用户
    @GetMapping("/getUserByUserId") // URL：localhost:8080/user/getUserByUserId  method:get
    public ResponseMessage<User> getUserById(@RequestParam int userId) {
        User user = userService.getUserByUserId(userId);
        return ResponseMessage.success(user);
    }

    // 根据手机号获取用户
    @GetMapping("/getUserByUserPhone") // URL：localhost:8080/user/getUserByUserPhone  method:get
    public ResponseMessage<User> getUserByPhone(@RequestParam String userPhone) {
        User user = userService.getUserByPhone(userPhone);
        if (user == null) {
            return new ResponseMessage<>(404, "用户不存在", null);
        }
        return ResponseMessage.success(user);
    }

    // 修改用户
    @PutMapping // URL：localhost:8080/user  method:put
    public ResponseMessage<User> updateUser(
            @RequestParam int userId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password,
            @RequestParam(required = false) String userPhone,
            @RequestParam(required = false) String birthDate,
            @RequestParam(required = false) String signature) {

        User userDetails = userService.getUserByUserId(userId);
        if (userDetails == null) {
            return new ResponseMessage<>(404, "用户不存在", null);
        }

        if (username != null) {
            userDetails.setUsername(username);
        }
        if (password != null) {
            userDetails.setPassword(password);
        }
        if (userPhone != null) {
            if (!userDetails.getUserPhone().equals(userPhone)) {
                if (userService.isUserPhoneExists(userPhone)) {
                    return new ResponseMessage<>(409, "手机号码已被注册，请使用其他手机号码。", null);
                }
                userDetails.setUserPhone(userPhone);
            }
        }
        if (birthDate != null) {
            userDetails.setBirthDate(LocalDate.parse(birthDate));
        }
        if (signature != null) {
            userDetails.setSignature(signature);
        }

        User userNew = userService.updateUser(userId, userDetails);
        return new ResponseMessage(200, "更新成功", userNew);
    }

    // 上传、修改头像
    @PostMapping("/uploadAvatar") // URL：localhost:8080/user/uploadAvatar  method:post
    public ResponseMessage<String> uploadAvatar(@RequestParam int userId, @RequestBody String avatar) {
        try {
            // 检查 avatar 是否为空
            if (avatar == null || avatar.isEmpty()) {
                return new ResponseMessage(400, "无效的头像数据", null);
            }

            // 去除Base64前缀
            if (avatar.startsWith("data:image")) {
                int commaIndex = avatar.indexOf(",");
                if (commaIndex == -1) {
                    return new ResponseMessage(400, "无效的Base64编码前缀", null);
                }
                avatar = avatar.substring(commaIndex + 1);
            }

            // 解码Base64字符串为字节数组
            byte[] avatarBytes = Base64.getDecoder().decode(avatar);

            // 验证头像数据大小
            int maxSize = 1024 * 1024; // 例如，最大1MB
            if (avatarBytes.length > maxSize) {
                return new ResponseMessage(400, "头像文件过大", null);
            }

            // 保存头像到文件系统
            String avatarPath = saveAvatarToFileSystem(userId, avatarBytes);
            if (avatarPath == null) {
                return new ResponseMessage(500, "头像保存失败", null);
            }

            // 更新用户头像路径
            User user = userService.getUserByUserId(userId);
            if (user == null) {
                return new ResponseMessage(404, "用户不存在", null);
            }
            user.setAvatar(avatarPath);
            // userService.saveUser(user);
            userService.updateUser(userId, user);
            return new ResponseMessage(200, "头像更新成功", user.getAvatar());
        } catch (IllegalArgumentException e) {
            return new ResponseMessage(400, "无效的Base64编码", null);
        } catch (Exception e) {
            return new ResponseMessage(500, "头像更新失败: " + e.getMessage(), null);
        }
    }

    // 删除用户
    @DeleteMapping // URL：localhost:8080/user method:delete
    public ResponseMessage<Void> deleteUser(@RequestParam int userId) {
        if (userService.deleteUser(userId)) {
            return new ResponseMessage<>(200, "删除成功", null);
        } else return new ResponseMessage<>(500, "删除失败", null);
    }

    // 保存头像到文件系统
    private String saveAvatarToFileSystem(int userId, byte[] avatarBytes) {
        try {
            // 构建文件路径
            String baseDir = "src/main/resources/static/avatar";
            Path directoryPath = Paths.get(baseDir);

            // 确保目录存在
            if (!Files.exists(directoryPath)) {
                Files.createDirectories(directoryPath);
            }

            // 构建文件路径
            String fileName = "avatar_" + userId + ".png"; // 假设头像格式为PNG
            Path avatarFilePath = Paths.get(baseDir, fileName);

            // 保存文件
            try (FileOutputStream fos = new FileOutputStream(avatarFilePath.toFile())) {
                fos.write(avatarBytes);
            }

            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取头像的Base64编码
    @GetMapping("/avatar") // URL：localhost:8080/user/avatar  method:get
    public ResponseMessage<String> getAvatarBase64(@RequestParam int userId) {
        String avatarBase64 = userService.getAvatarBase64(userId);
        if (avatarBase64 == null) {
            return new ResponseMessage<>(404, "用户不存在或未设置头像", null);
        }
        // 添加Base64前缀
        String avatarWithPrefix = "data:image/png;base64," + avatarBase64;
        return new ResponseMessage<>(200, "获取头像成功", avatarWithPrefix);
    }

    // 测试接口：获取本地的图片
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/avatar/local") // URL：localhost:8080/user/avatar/local  method:get
    public ResponseMessage<String> getLocalAvatar() {
        String avatarPath = "http://localhost:8080/cover1.jpg";
        return new ResponseMessage<>(200, "获取头像成功", avatarPath);
    }
}
